package group32.server;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import group32.client.HomePageService;
import group32.shared.UpdateInfo;


import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class HomePageServiceImpl extends RemoteServiceServlet implements
		HomePageService {

	public List<UpdateInfo> updates(int userID) throws IllegalArgumentException{
		List<String> l = new ArrayList<String>();
		List<UpdateInfo> U= new ArrayList<UpdateInfo>();
		//if(this.getThreadLocalRequest().getSession().getAttribute(userID+"")!=null){
			ResultSet rs=new Connect().getUpdates(userID);
			try {
				while(rs.next()){
					String fn=rs.getString("firstname");
					String ln=rs.getString("lastname");
					int photoid=rs.getInt("photoID");
					Timestamp date = rs.getTimestamp("ts");
					String url = rs.getString("url");
					String s=fn+" "+ln+" added a new picture "+photoid + " at time " + date;
					UpdateInfo ui= new UpdateInfo();
					ui.type="Upload";
					ui.firstName=fn;
					ui.lastName=ln;
					ui.photoID=photoid;
					ui.timestamp= date;
					ui.url=url;
					l.add(s);
					U.add(ui);
					//System.out.println(s);
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ResultSet rs1=new Connect().getTagsUpdates(userID);
			try {
				while(rs1.next()){
					String fn=rs1.getString("firstname");
					String ln=rs1.getString("lastname");
					String tag=rs1.getString("tag");
					int photoid=rs1.getInt("photoID");
					Timestamp date = rs1.getTimestamp("ts");
					String url = rs1.getString("url");
					String s=fn+" "+ln+" tagged picture "+photoid +" with tag "+tag+ "at time " + date;
					l.add(s);
					UpdateInfo ui= new UpdateInfo();
					
					ui.type="Tag";
					ui.firstName=fn;
					ui.lastName=ln;
					ui.photoID=photoid;
					ui.timestamp= date;
					ui.url= url;
					l.add(s);
					U.add(ui);
					//System.out.println(s);
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		//}
			Collections.sort(U);
		return U;
	}

	@Override
	public String getUserType(int userID) throws IllegalArgumentException {
		String s =null;
		ResultSet rs2=new Connect().getUserType(userID);
		try {rs2.next();
			s= rs2.getString("type");
			return s;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
